class Snake {
    elemnt: HTMLElement
    head: HTMLElement
    bodies: NodeList

    constructor() {
        this.elemnt = document.querySelector('.snake')
        this.head = document.querySelector('.snake div:first-child')
        this.bodies = document.querySelectorAll('.snake div')
    }

    // 获取蛇头X轴坐标
    get X() {
        return this.head.offsetLeft
    }

    // 获取蛇头Y轴坐标
    get Y() {
        return this.head.offsetTop
    }

    // 设置蛇头X轴坐标
    set X(value) {
        if (this.X === value)
        return

        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了')
        }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value) {

            if (this.X > value) {
                value = this.X + 10
            } else {
                value = this.X - 10
            }
        }

        this.moveBody()

        this.head.style.left = value + 'px'
        this.checkHeadBody()
    }

    // 设置蛇头Y轴坐标
    set Y(value) {
        if (this.Y === value)
        return

        if (value < 0 || value > 290) {
            throw new Error('蛇撞墙了')
        }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {

            if (this.Y > value) {
                value = this.Y + 10
            } else {
                value = this.Y - 10
            }
        }
        
        this.moveBody()
    
        this.head.style.top = value + 'px'
        this.checkHeadBody()
    }

    addBody() {
        const div  = document.createElement('div')
        this.elemnt.appendChild(div)
        this.bodies = document.querySelectorAll('.snake div')
    }

    moveBody() {
        // 后面的身体，移动到前面身体的位置
        for (let i = this.bodies.length - 1; i > 0; i--) {
            const curNode = this.bodies[i] as HTMLElement
            const frontNode = this.bodies[i - 1] as HTMLElement

            curNode.style.left = frontNode.offsetLeft + 'px'
            curNode.style.top = frontNode.offsetTop + 'px'
        }
    }

    checkHeadBody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            const curNode = this.bodies[i] as HTMLElement

            if (this.X === curNode.offsetLeft && this.Y === curNode.offsetTop) {
                throw new Error('撞到自己')
            }
        }
    }
}

export default Snake
